package com.fjd.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fjd.constant.LiveConstant;
import com.fjd.context.BaseContext;
import com.fjd.dto.FollowDTO;
import com.fjd.dto.IMUserDTO;
import com.fjd.dto.MiniMallCheckDTO;
import com.fjd.dto.MiniMallDeleteDTO;
import com.fjd.entity.Follow;
import com.fjd.entity.LiveBroadcast;
import com.fjd.entity.MerchandiseInfo;
import com.fjd.entity.MiniMall;
import com.fjd.mapper.*;
import com.fjd.service.LiveService;
import com.fjd.utils.HttpClientUtil;
import com.fjd.vo.AttentionVO;
import com.fjd.vo.LiveDataVO;
import com.fjd.vo.MerchandiseVO;
import com.fjd.vo.WatcherInitialVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tencentyun.TLSSigAPIv2;

import java.io.IOException;
import java.util.*;

@Service
public class LiveServiceImpl implements LiveService {

    @Autowired
    private MinimallMapper minimallMapper;
    @Autowired
    private MerchandiseInfoMapper merchandiseInfoMapper;
    @Autowired
    private ProductImageMapper productImageMapper;
    @Autowired
    private ShoppingProductMapper shoppingProductMapper;
    @Autowired
    private LiveBroadcastMapper liveBroadcastMapper;
    @Autowired
    private ShoppingCustomerInfoMapper shoppingCustomerInfoMapper;
    @Autowired
    private FollowerMapper followerMapper;
    @Autowired
    private SalesOrderMapper salesOrderMapper;

    private static final String IM_USER_CREATE = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=1600063777&identifier=administrator&usersig=eJwtjF0LgjAYRv-LrkM27XUqdBGEgRUUitrlcLNezA*2UUH03zP18jnn4XxIdkydp9IkIq5DyWraKFVnscYJC9lih8ZqYXu9HIxsxDCgJBHzKaW*xzmfjXoPqNXIAcAd1Uwttn-GPc4YZaG-VPA29pM4BSgvB8irF8S7Ps-y86PYm7VJg9Cltj4l23vRlFcv2JDvDz8YM*k_";

    private static final String IM_GROUP_CREATE = "https://console.tim.qq.com/v4/group_open_http_svc/create_group?sdkappid=1600063777&identifier=administrator&usersig=eJwtzF0LgjAYBeD-sttCpjInQhdKmFL0YdG9ulUvNZtzWRb995Z6eZ5zOB90WO2tlisUIMfCaNpnYLzScIKecyaggkarXN-VOGjYNZcSGApsD2PsuZTSoeEvCYobJ4Q4phpUg-gbdalNjfvjC5zNf5Lusrq7LeaPbUySYrKUx*a5zgop3vUmjrowrQs-bC9lGc7Q9wdoHTWH";

    @Override
    public List<MerchandiseVO> listMinimallByAnchorId(String anchorId) {
        List<String> merchandiseIds = minimallMapper.getByAnchorId(anchorId);
        List<MerchandiseVO> merchandiseVOList = new ArrayList<>();
        if(merchandiseIds != null && merchandiseIds.size()!=0) {
            List<MerchandiseInfo> merchandiseInfoList = merchandiseInfoMapper.getByIds(merchandiseIds);
            merchandiseVOList = convertMerchandiseInfoListToMerchandiseVOList(merchandiseInfoList);
        }
        return merchandiseVOList;
    }

    public List<MerchandiseVO> convertMerchandiseInfoListToMerchandiseVOList(List<MerchandiseInfo> merchandiseInfoList){
        List<MerchandiseVO> merchandiseVOList = new ArrayList<>();
        for (MerchandiseInfo mdI:merchandiseInfoList){
            MerchandiseVO merchandiseVO = new MerchandiseVO();
            BeanUtils.copyProperties(mdI,merchandiseVO);
            merchandiseVOList.add(merchandiseVO);
        }

        for(MerchandiseVO md : merchandiseVOList){

            //确定商品对应的图片列表
            List<String> images = productImageMapper.getByProductId(md.getMerchandiseId());
            md.setImageList(images);

            //针对每一个商品 在商品列表页展示的价格应该为该商品下某一个规格的最低价格
            //例子可以参考MerchandiseVO中对price字段的注解
            md.setPrice(shoppingProductMapper.getCheapestPrice(md.getMerchandiseId()));

        }
        return merchandiseVOList;
    }

    @Override
    public Boolean check(MiniMallCheckDTO miniMallCheckDTO) {
        String anchorId = BaseContext.getCurrentId().toString();
        List<String> merchandiseIds = minimallMapper.getByAnchorId(anchorId);
        for (String id:merchandiseIds){
            if(id.equals(miniMallCheckDTO.getMerchandiseId())){
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }

    @Override
    public void add(MiniMallCheckDTO miniMallCheckDTO) {
        String merchandiseId=miniMallCheckDTO.getMerchandiseId();
        String anchorId = BaseContext.getCurrentId().toString();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        MiniMall miniMall = MiniMall.builder()
                .id(uuid)
                .customerId(anchorId)
                .merchandiseId(merchandiseId)
                .build();
        minimallMapper.insert(miniMall);
    }

    @Override
    public void delete(MiniMallDeleteDTO miniMallDeleteDTO) {
        List<String> merchandiseIds = miniMallDeleteDTO.getMerchandiseIds();
        String anchorId = BaseContext.getCurrentId().toString();
        minimallMapper.deleteByMerchandiseIds(merchandiseIds,anchorId);
    }

    /**
     * 创建IM用户
     */
    @Override
    public Boolean createIMUser(IMUserDTO imUserDTO){

        //创建IM用户
        JSONObject jsonObject = IMUserCreate(imUserDTO.getOpenId(), imUserDTO.getNickName(), imUserDTO.getAvatarUrl());
        String actionStatus = jsonObject.getString("ActionStatus");


        //创建IM群组
        Random random = new Random();
        long randomUnsignedInt = random.nextInt() & 0xFFFFFFFFL;
        String ran = String.valueOf(randomUnsignedInt);
        String groupUrl =IM_GROUP_CREATE + "&random=" + ran + "&contenttype=json";
        Map<String,String> groupmap =new HashMap<>();
        groupmap.put("Owner_Account",imUserDTO.getOpenId());
        groupmap.put("Type","AVChatRoom");
        groupmap.put("Name","直播间");
        groupmap.put("GroupId",imUserDTO.getOpenId());

        String groupjson = null;
        try {
            groupjson = HttpClientUtil.doPost4Json(groupUrl, groupmap);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JSONObject jsonObject2 = JSON.parseObject(groupjson);
        String actionStatus2 = jsonObject2.getString("ActionStatus");

        if (actionStatus.equals("OK") && actionStatus2.equals("OK")){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Override
    public List<LiveBroadcast> listliveroom() {
        List<LiveBroadcast> liveBroadcastList = liveBroadcastMapper.list();
        return liveBroadcastList;
    }

    @Override
    public WatcherInitialVO enter(String openId) {
        String customerId = BaseContext.getCurrentId().toString();
        String username = shoppingCustomerInfoMapper.getUsernameById(customerId);
        String avatar = shoppingCustomerInfoMapper.getAvatarById(customerId);

        //为刚进入直播间的用户新增一个IMUser
        IMUserCreate(openId,username,avatar);

        //生成TLSSig
        TLSSigAPIv2 api = new TLSSigAPIv2(Long.parseLong(LiveConstant.SDK_APP_ID), LiveConstant.KEY);

        String userSig = api.genUserSig(openId, 180*86400);
        System.out.print(userSig);

        WatcherInitialVO watcherInitialVO = WatcherInitialVO.builder()
                .SDKAppID(LiveConstant.SDK_APP_ID)
                .userSig(userSig)
                .userName(openId)
                .build();

        return watcherInitialVO;
    }


    public JSONObject IMUserCreate(String openId,String Nick,String FaceUrl){
        Random random = new Random();
        long randomUnsignedInt = random.nextInt() & 0xFFFFFFFFL;
        String ran = String.valueOf(randomUnsignedInt);
        String userUrl = IM_USER_CREATE + "&random=" + ran + "&contenttype=json";
        Map<String,String> usermap = new HashMap<>();
        usermap.put("UserID",openId);
        usermap.put("Nick",Nick);
        usermap.put("FaceUrl",FaceUrl);
        String userjson = null;
        try {
            userjson = HttpClientUtil.doPost4Json(userUrl, usermap);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JSONObject jsonObject = JSON.parseObject(userjson);
        return jsonObject;
    }

    @Override
    public void editLiveStatus(String status) {
        String customerId = BaseContext.getCurrentId();
        liveBroadcastMapper.updateStatus(status,customerId);
    }

    @Override
    public void follow(FollowDTO followDTO) {
         if (followDTO.getIsFollowed()){
             followerMapper.insert(followDTO.getFromId(),followDTO.getToId());
         }
         else{
             followerMapper.delete(followDTO.getFromId(),followDTO.getToId());
         }
    }

    @Override
    public List<AttentionVO> listAttention() {
        String fromId = BaseContext.getCurrentId();
        List<Follow> followList = followerMapper.list(fromId);
        List<AttentionVO> attentionVOList = new ArrayList<>();
        for (Follow f:followList){
            AttentionVO attentionVO = new AttentionVO();
            String anchorId = f.getToId();
            attentionVO.setNick(shoppingCustomerInfoMapper.getUsernameById(anchorId));
            attentionVO.setAvatar(shoppingCustomerInfoMapper.getAvatarById(anchorId));
            attentionVOList.add(attentionVO);
        }
        return attentionVOList;
    }

    @Override
    public Follow checkFollow(String toId) {
        String fromId = BaseContext.getCurrentId();
        Follow follow = followerMapper.getByFromIdAndToId(fromId,toId);
        return follow;
    }

    @Override
    public LiveDataVO getLiveData() {
        String anchorId = BaseContext.getCurrentId();
        LiveDataVO liveDataVO = LiveDataVO.builder()
                .FollowerCount(followerMapper.getFollowSum(anchorId))
                .OrderCount(salesOrderMapper.getLiverOrderCount(anchorId))
                .Amount(salesOrderMapper.getLiverAmountCount(anchorId))
                .build();
        return liveDataVO;
    }
}
